package com.shouer.doc.ui.neworder;

import android.content.Intent;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.shouer.doc.R;
import com.shouer.doc.application.App;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.ScreenUtils;
import com.shouer.doc.dialog.ShouerLoadingDialogUtil;
import com.shouer.doc.ui.LasyFragment;
import com.shouer.doc.ui.healthreportedit.HealthReportEditActivity;
import com.shouer.doc.ui.login.model.UserModel;
import com.shouer.doc.ui.neworder.adapter.HealthRecordAdapter;
import com.shouer.doc.ui.neworder.adapter.NewOrderAdapter;
import com.shouer.doc.ui.neworder.model.HealthRecord;
import com.shouer.doc.ui.neworder.model.SimpleOrderModel;
import com.shouer.doc.ui.neworder.presenter.INewOrderPresenter;
import com.shouer.doc.ui.neworder.presenter.NewOrderListPresenterCompl;
import com.shouer.doc.ui.neworder.response.QueryHealthOrderResponse;
import com.shouer.doc.ui.neworder.view.INewOrdView;
import com.shouer.doc.widget.OrderItemDecoration;
import com.shouer.doc.widget.ShouerLayoutManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imlib.model.Conversation;

/**
 * Created by ZXL on 2016/11/25.
 */

public class NewOrderFragment extends LasyFragment implements INewOrdView {

    private View mRootView;
    private boolean isPrepared = false;

    @BindView(R.id.tap_layout)
    protected View tapLayout;
    @BindView(R.id.tap1)
    protected View tap1;
    @BindView(R.id.tap2)
    protected View tap2;

    @BindView(R.id.new_order_layout)
    protected View newOrderLayout;
    @BindView(R.id.new_order_list)
    protected XRecyclerView newOrderListView;
    @BindView(R.id.tips_view)
    protected TextView tipsView;
    private NewOrderAdapter orderListAdapter;

    @BindView(R.id.health_order_layout)
    protected View healthOrderLayout;
    @BindView(R.id.health_order_list)
    protected XRecyclerView healthOrderListView;
    @BindView(R.id.health_tips_view)
    protected TextView healthTipsView;
    private HealthRecordAdapter healthRecordAdapter;

    @BindView(R.id.navigation_view)
    protected ImageView navigationView;
    private Animation animation;
    private int offset, one;

    private App app;
    private INewOrderPresenter newOrderPresenter;
    private boolean isFirst = true;


    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        app = (App) getActivity().getApplicationContext();
        newOrderPresenter = new NewOrderListPresenterCompl(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (null == mRootView) {
            mRootView = inflater.inflate(R.layout.fragment_neworder_layout, container, false);
            ButterKnife.bind(this, mRootView);

            ShouerLayoutManager layoutManager = new ShouerLayoutManager(getContext());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            newOrderListView.setLayoutManager(layoutManager);
            newOrderListView.addItemDecoration(new OrderItemDecoration(ScreenUtils.dip2px(getContext(), 15)));

            orderListAdapter = new NewOrderAdapter(getContext(), null, this);
            newOrderListView.setAdapter(orderListAdapter);
            newOrderListView.setRefreshProgressStyle(ProgressStyle.SquareSpin);
            newOrderListView.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
            newOrderListView.setLoadingListener(new XRecyclerView.LoadingListener() {
                @Override
                public void onRefresh() {
                    //refresh data here
                    Log.d(XRecyclerView.class.getSimpleName(), "onRefresh()");
                    if (!newOrderPresenter.refresh()) {
                        newOrderListView.refreshComplete();
                    }
                }

                @Override
                public void onLoadMore() {
                    // load more data here
                    Log.d(XRecyclerView.class.getSimpleName(), "onLoadMore()");
                    if (!newOrderPresenter.loadMore()) {
                        newOrderListView.loadMoreComplete();
                    }
                }
            });


            ShouerLayoutManager layoutManager2 = new ShouerLayoutManager(getContext());
            layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
            healthOrderListView.setLayoutManager(layoutManager2);
            healthOrderListView.addItemDecoration(new OrderItemDecoration(ScreenUtils.dip2px(getContext(), 15)));

            healthRecordAdapter = new HealthRecordAdapter(getContext(), null, this);
            healthOrderListView.setAdapter(healthRecordAdapter);
            healthOrderListView.setRefreshProgressStyle(ProgressStyle.SquareSpin);
            healthOrderListView.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
            healthOrderListView.setLoadingListener(new XRecyclerView.LoadingListener() {
                @Override
                public void onRefresh() {
                    //refresh data here
                    Log.d(XRecyclerView.class.getSimpleName(), "onRefresh()");
                    if (!newOrderPresenter.refreshHealthRecord()) {
                        healthOrderListView.refreshComplete();
                    }
                }

                @Override
                public void onLoadMore() {
                    // load more data here
                    Log.d(XRecyclerView.class.getSimpleName(), "onLoadMore()");
                    if (!newOrderPresenter.loadMoreHealthRecord()) {
                        healthOrderListView.loadMoreComplete();
                    }
                }
            });

            tap1.setSelected(true);

            int imgWidth = (int) getResources().getDimension(R.dimen.navigation_img_width);
            offset = (ScreenUtils.getScreenWidth(getContext()) / 2 - imgWidth) / 2;
            one = ScreenUtils.getScreenWidth(getContext()) / 2;
            Matrix matrix = new Matrix();
            matrix.postTranslate(offset, 0);
            navigationView.setImageMatrix(matrix);// 设置动画初始位置

            if (app.getUserDocInfo().getRecordAccessRight() == 0) {
                tapLayout.setVisibility(View.GONE);
            } else {
                tapLayout.setVisibility(View.VISIBLE);
            }

            isPrepared = true;
            lazyLoad();
        }
        return mRootView;
    }


    private void setSelectedForDirectiveImg(int position) {

        if (position == 0) {
            animation = new TranslateAnimation(one, 0, 0, 0);
        } else {
            animation = new TranslateAnimation(0, one, 0, 0);
        }
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        navigationView.startAnimation(animation);

    }

    @OnClick(value = {R.id.tap1, R.id.tap2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tap1:
                if (newOrderLayout.getVisibility() != View.VISIBLE) {
                    tap2.setSelected(false);
                    tap1.setSelected(true);
                    setSelectedForDirectiveImg(0);
                    healthOrderLayout.setVisibility(View.GONE);
                    newOrderLayout.setVisibility(View.VISIBLE);

                    if (orderListAdapter.getItemCount() == 0) {
                        newOrderPresenter.refresh();
                    }
                }
                break;
            case R.id.tap2:
                if (healthOrderLayout.getVisibility() != View.VISIBLE) {
                    tap1.setSelected(false);
                    tap2.setSelected(true);
                    setSelectedForDirectiveImg(1);
                    newOrderLayout.setVisibility(View.GONE);
                    healthOrderLayout.setVisibility(View.VISIBLE);

                    if (healthRecordAdapter.getItemCount() == 0) {
                        newOrderPresenter.refreshHealthRecord();
                    }
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        newOrderPresenter.onDestroy();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        if (isFirst) {
            isFirst = false;
            ShouerLoadingDialogUtil.getInstance().show(getContext());
        }
        if (newOrderLayout.getVisibility() == View.VISIBLE) {
            newOrderPresenter.refresh(true);
        } else {
            newOrderPresenter.refreshHealthRecord(true);
        }
    }


    @Override
    public App getApp() {
        return app;
    }

    @Override
    public UserModel getUser() {
        return app.getUserModel();
    }

    @Override
    public void newOrderItemClick(SimpleOrderModel orderModel) {

    }

    @Override
    public void receiveOrder(SimpleOrderModel orderModel) {
        if (app.isUserLogin()) {
            newOrderPresenter.receiveOrder(orderModel);
        }
    }

    @Override
    public void refuseOrder(SimpleOrderModel orderModel) {
        if (app.isUserLogin()) {
            newOrderPresenter.refuseOrder(orderModel);
        }
    }

    @Override
    public void refreshOrderList(List<SimpleOrderModel> simpleOrderModels) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Log.i(NewOrderFragment.class.getSimpleName(), "refreshOrderList");
        newOrderListView.refreshComplete();
        newOrderListView.loadMoreComplete();
        if (null != orderListAdapter) {
            orderListAdapter.refreshDocList(simpleOrderModels);
        }
        if (null == simpleOrderModels || simpleOrderModels.size() == 0) {
            tipsView.setVisibility(View.VISIBLE);
        } else {
            tipsView.setVisibility(View.GONE);
        }
    }

    @Override
    public void attachOrdList(List<SimpleOrderModel> simpleOrderModels) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        tipsView.setVisibility(View.GONE);
        Log.i(NewOrderFragment.class.getSimpleName(), "attachOrdList");
        newOrderListView.refreshComplete();
        newOrderListView.loadMoreComplete();
        if (null != orderListAdapter) {
            orderListAdapter.attachToDocList(simpleOrderModels);
        }
    }

    @Override
    public void loadOrdDataFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        newOrderListView.refreshComplete();
        newOrderListView.loadMoreComplete();
        Toast.makeText(getContext(), failInfo, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void receiveOrderSuccess(SimpleOrderModel orderModel) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Log.i(NewOrderFragment.class.getSimpleName(), "receiveOrderSuccess");
        orderListAdapter.removeOrder(orderModel);
        newOrderPresenter.refresh();
        if (orderModel.getOrderType() == 1 || orderModel.getOrderType() == 4) {
            //图文咨询或者首儿送药
            String title = null;
            if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_YAO) {
                title = getResources().getString(R.string.ORDER_NAME_YAO);//挂号送药
            } else if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_SHIPING) {
                title = getResources().getString(R.string.ORDER_NAME_SHIPING);//视频咨询
            } else if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_DIANHUA) {
                title = getResources().getString(R.string.ORDER_NAME_DIANHUA);//电话咨询
            } else {
                if (orderModel.getChannel() == 9) {
                    title = getResources().getString(R.string.ORDER_NAME_HEALTHRECORD);//健康报告咨询
                } else {
                    if ("0".equals(orderModel.getFreeType())) {
                        title = getResources().getString(R.string.ORDER_NAME_TUWEN_FREE);//免费导诊
                    } else {
                        title = getResources().getString(R.string.ORDER_NAME_TUWEN);//图文咨询
                    }
                }

            }
            Uri uri = Uri.parse("rong://" + getContext().getApplicationInfo().packageName).buildUpon().appendPath("conversation").appendPath(Conversation.ConversationType.GROUP.getName().toLowerCase()).
                        appendQueryParameter("targetId", orderModel.getOrderId()).appendQueryParameter("title", title).build();
            Intent intent = new Intent("android.intent.action.VIEW", uri);

            intent.putExtra("order_info", orderModel);
            getContext().startActivity(intent);

        }

    }

    @Override
    public void receiveOrderFailed(String info) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(getContext(), info, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void orderHasBeReceived(SimpleOrderModel orderModel, String info) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(getContext(), info, Toast.LENGTH_SHORT).show();
        orderListAdapter.removeOrder(orderModel);
        newOrderPresenter.refresh();
    }

    @Override
    public void receiveHealthRecordSuccess(HealthRecord record) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Log.i(NewOrderFragment.class.getSimpleName(), "receiveHealthRecordSuccess");
        healthRecordAdapter.removeHealthRecord(record);
        newOrderPresenter.refreshHealthRecord();

        Intent intent = new Intent(getContext(), HealthReportEditActivity.class);
        intent.putExtra("recId", record.getRecid());
        startActivity(intent);

    }

    @Override
    public void receiveHealthRecordFailed(String info) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(getContext(), info, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void healthRecordHasBeReceived(HealthRecord record, String info) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(getContext(), info, Toast.LENGTH_SHORT).show();
        healthRecordAdapter.removeHealthRecord(record);
        newOrderPresenter.refreshHealthRecord();
    }

    @Override
    public void refuseOrderSuccess(SimpleOrderModel orderModel) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Log.i(NewOrderFragment.class.getSimpleName(), "receiveOrderSuccess");
        orderListAdapter.removeOrder(orderModel);
        newOrderPresenter.refresh();
    }

    @Override
    public void refuseOrderFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(getContext(), failInfo, Toast.LENGTH_SHORT).show();
    }

    /**
     * 刷新健康档案订单列表
     */
    @Override
    public void refreshHealthOrderList(QueryHealthOrderResponse response) {

        ShouerLoadingDialogUtil.getInstance().dismiss();
        Log.i(NewOrderFragment.class.getSimpleName(), "refreshHealthOrderList");
        healthOrderListView.refreshComplete();
        healthOrderListView.loadMoreComplete();
        if (null != healthRecordAdapter) {
            healthRecordAdapter.refreshHealthRecordList(response.getRecordList());
        }
        if (null == response.getRecordList() || response.getRecordList().size() == 0) {
            healthTipsView.setVisibility(View.VISIBLE);
        } else {
            healthTipsView.setVisibility(View.GONE);
        }

    }

    /**
     * 加载更多健康档案订单
     */
    @Override
    public void attachHealthOrdList(QueryHealthOrderResponse response) {

        ShouerLoadingDialogUtil.getInstance().dismiss();
        healthTipsView.setVisibility(View.GONE);
        Log.i(NewOrderFragment.class.getSimpleName(), "attachHealthOrdList");
        healthOrderListView.refreshComplete();
        healthOrderListView.loadMoreComplete();
        if (null != healthRecordAdapter) {
            healthRecordAdapter.attachToHealthRecordList(response.getRecordList());
        }

    }

    /**
     * 查询健康档案订单失败
     */
    @Override
    public void loadHealthOrdDataFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        healthOrderListView.refreshComplete();
        healthOrderListView.loadMoreComplete();
        Toast.makeText(getContext(), failInfo, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void receiveHealthRecord(HealthRecord record) {
        ShouerLoadingDialogUtil.getInstance().show(getContext());
        newOrderPresenter.receiveHealthRecord(record);
    }
}
